package view;

import model.Table;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 * Display in Bar Chart Graph
 * @author David, Rex
 */
public class BarChartMode extends GeneralDisplayMode {
    //sort according to this column

    /**
     * construct bar chart
     * @param dataTable sub-table of data
     * @param categoryNames categories to be displayed
     */
    public BarChartMode (Table dataTable, String[] categoryNames) {
        super(dataTable, categoryNames);
        setSortIndex(1);
    }

    @Override
    /**
     * make the graph according to the given dataTable
     * a panel on which the graph is drawn
     */
    public ChartPanel constructChartPanel () {
        JFreeChart chart = ChartFactory.createBarChart("Bar Chart Plot",
                /* x axis label*/ getCategoryNames()[0], 
                /* y axis label*/ "",
                /* data*/ createDataset(),
                /* include legend*/ PlotOrientation.VERTICAL, false,
                /* tooltips*/ false, 
                /* urls*/false);
        ChartPanel panel = new ChartPanel(chart, true);
        return panel;
    }

    private CategoryDataset createDataset () {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; i < getDataSize(); i++) {
            try {
                dataset.addValue(Double.parseDouble(getTable().getData(i, 1).getValue()),
                        "set1", getTable().getData(i, 0).getValue().toString());
            }
            catch (ClassCastException e) {
                /*
                 * this should not happen because the type of data in the
                 * available categories have already been checked to be doubles
                 */
                e.printStackTrace();
            }
        }
        return dataset;
    }

    /**
     * sort in ascending order
     */
    public void sortAscending () {
        getTable().sortAscending(getSortIndex());
    }

    /**
     * sort in descending order
     */
    public void sortDescending () {
        getTable().sortDescending(getSortIndex());
    }

}
